<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="日期" prop="dateInfo" clearable>
        <el-date-picker clearable v-model="queryParams.dateInfo" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择日期">
        </el-date-picker>
      </el-form-item>

      <!-- <el-form-item label="员工姓名">
        <el-select v-model="queryParams.uid" placeholder="请选择用户" clearable filterable>
          <el-option v-for="user in userInfoList" :key="user.uid" :label="user.nickName" :value="user.uid"></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="small" @click="handleAdd"
          v-hasPermi="['merchantdata:userInfo:add']">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userInfoList">
      <el-table-column label="姓名" align="center" prop="nickName" />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="已分配数量" align="center" prop="total" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch :value="!scope.row.status" @change="handleStatusChange(scope.row, $event)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['merchantdata:userInfo:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改商户成员信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入员工姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号码" />
        </el-form-item>
      </el-form>
      <p style="color: red; text-align: center;">密码默认为手机号后六位</p>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { listUserInfo, changeUserStatus, delUserInfo, addUserInfo, updateUserInfo } from "@/api/merchantdata/userInfo";

export default {
  name: "UserInfo",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商户成员信息表格数据
      userInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dateInfo: null,
        infoId: null,
        nickName: null,
        uid: null
      },
      // 表单参数
      form: {
        phone: '',
      },
      // 表单校验
      rules: {
        nickName: [
          { required: true, message: '请输入员工姓名', trigger: 'blur' }, // 非空校验
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' }, // 非空校验
          {
            pattern: /^1\d{10}$/, // 手机号正则表达式，这里假设是11位数字
            message: '请输入正确的手机号格式',
            trigger: 'blur',
          },
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleStatusChange(row, value) {
      const text = row.status == 0 ? "停用" : "启用"; // 修改启用和停用的文本
      this.$modal.confirm('确认要"' + text + ':' + row.nickName + '"用户吗？').then(() => {
        // 创建要发送的JSON对象
        const requestData = {
          uid: row.uid,
          status: row.status == 0 ? 1 : 0, // 反转状态
        };
        // 发送JSON数据给后台
        return changeUserStatus(requestData);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
        this.getList();
      }).catch(() => {
        // 如果出错，将状态值设置回原始值
        row.status = row.status == 0 ? 1 : 0; // 反转状态
      });
    },


    formatPhoneNumber(value) {
      return value;
    },
    validatePhoneNumber(row) {
      const phoneNumberPattern = /^1\d{10}$/;

      if (!phoneNumberPattern.test(row.userName)) {
        this.$message.error("请输入正确的手机号格式");
        row.userName = "";
      }
    },
    /** 查询商户成员信息列表 */
    getList() {
      this.loading = true;
      listUserInfo(this.queryParams).then(response => {
        this.userInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        infoId: null,
        deptId: null,
        dateInfo: null,
        nickName: null,
        uid: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.uid = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商户成员信息";
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateUserInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUserInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const uid = row.uid 
      const nickName = row.nickName 
      this.$modal.confirm('是否删除成员' + nickName + '？').then(function () {
        return delUserInfo(uid);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('merchantdata/userInfo/export', {
        ...this.queryParams
      }, `userInfo_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
